package com.valveinspectionsys.order.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.valveinspectionsys.R;
import com.valveinspectionsys.dbhelp.XmlNameHelper;
import com.valveinspectionsys.gridview.ImageSwitcherActivity;
import com.valveinspectionsys.order.db.OrderDao;
import com.valveinspectionsys.povo.DeviceVo;
import com.valveinspectionsys.povo.SpinnerVo;
import com.valveinspectionsys.util.DateUtil;
import com.valveinspectionsys.util.FileNameUtil;
import com.valveinspectionsys.util.SharedPreferenceUtil;
import com.valveinspectionsys.util.TipHelper;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.provider.MediaStore.Audio.Media;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

/**
 * 无法用RFID读卡的设备工程单
 * @author King
 *2013-5-6
 */
public class OrderAddNoRfidActivity extends Activity  implements OnClickListener{
    private static final int REQUEST_CODE_TAKE_VIDEO = 2;
    private static final int REQUEST_CODE_TAKE_IMAGE = 1;
    private static final int REQUEST_CODE_TAKE_SOUND = 3;
    private final static int DIALOG = 1;
    public static final int ITEM0 = Menu.FIRST;// 系统值
    public ProgressDialog pd;

    public int OrderID = 0;
   
    public String videopath;
    public boolean isupload = false;
    public String soundpath;
    public String type = "无";
    public String typeName="无";//类型名称
    public Button button1;// 保存
    
    public Button button3;// 上传
    public EditText edit1;// 名称
    public EditText edit2;// 描述
    public Spinner spinner;// 类型
    public Button button4;// 定位
   
    public LocationClient client;
    public Double latitude = 0.0;// 维度
    public Double longitude = 0.0;// 径度
    public SharedPreferenceUtil sp;
    public OrderDao   dao;
    public List<SpinnerVo> spinnerinfo=new ArrayList<SpinnerVo>();
    public boolean isImg=false;
    public FileNameUtil  f=null;
    public String deviceid;
    public TextView textview1;// 水表编号
    public TextView textview2;// 水表地址

    @Override
    protected void onCreate(Bundle savedInstanceState) {

	super.onCreate(savedInstanceState);
	setContentView(R.layout.order_norfid);
	deviceid=getIntent().getStringExtra("deviceid");
	latitude=getIntent().getDoubleExtra("latitude", 0.0);
	longitude=getIntent().getDoubleExtra("longitude", 0.0);
	sp = new SharedPreferenceUtil(this);
	dao=new OrderDao(this, sp.getValue(XmlNameHelper.SqliteName));
 
	f=new FileNameUtil();
	init();
    }

    public void init() {
	OrderID=dao.InsertOrder();
	edit1 = (EditText) findViewById(R.id.order_norfid_ordername);
	edit2 = (EditText) findViewById(R.id.order_norfid_desc);
	spinner = (Spinner) findViewById(R.id.order_norfid_ordertype);
	button1 = (Button) findViewById(R.id.order_norfid_save);
	button4 = (Button) findViewById(R.id.order_norfid_upload);
	
	textview2 = (TextView) findViewById(R.id.order_norfid_textview_wateradds);
	textview1 = (TextView) findViewById(R.id.order_norfid_textView_waternumber);
	textview1.setText("");
	textview2.setText("");
	DeviceVo device=dao.queryDevice(null, deviceid);
	textview1.setText(device.getDeviceNumber());
	textview2.setText(device.getDeviceAdds());
	button4.setOnClickListener(this);
	button1.setOnClickListener(this);
	

	// 选择工程类型监听器
	spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

	    @Override
	    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		SpinnerVo s=(SpinnerVo)arg0.getSelectedItem();
		type=s.getKey();
	    }

	    @Override
	    public void onNothingSelected(AdapterView<?> arg0) {
		type = "无";

	    }
	});

	spinnerinfo=dao.queryOrderType();
	
	ArrayAdapter<SpinnerVo> ada = new ArrayAdapter<SpinnerVo>(this, android.R.layout.simple_spinner_item, spinnerinfo);// 放数据
	ada.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	spinner.setAdapter(ada);

    }

    @Override
    public void onClick(View v) {
	 if (button1.getId() == v.getId()) {	 
	    if (type.equals("无")||type.equals("0")) {
		Toast.makeText(this, "请选择工程单类型", Toast.LENGTH_SHORT).show();
		return;
	    }
	    if (isImg) {
		showDialog(DIALOG + 1);
	    } else {
		Toast.makeText(this, "这种情况须拍照", Toast.LENGTH_SHORT).show();
		return;
	    }

	} else if (v.getId() == button4.getId()) {
	    Intent intent = new Intent(OrderAddNoRfidActivity.this, ImageSwitcherActivity.class);
	     intent.putExtra("otherid",OrderID+"" );
	     intent.putExtra("status", "-1");
	     intent.putExtra("devicelistid", "-2");
	    startActivityForResult(intent, REQUEST_CODE_TAKE_IMAGE);
	}

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

	
	menu.add(0, ITEM0 + 2, 0, "录视频");
	menu.add(0, ITEM0 + 3, 0, "录音");

	menu.findItem(ITEM0 + 1);

	return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

	switch (item.getItemId()) {

	case ITEM0 + 1:
	   
	    break;
	case ITEM0 + 2:
	    if(!TextUtils.isEmpty(videopath)){
		f.delectFile(videopath);
	    }
	    videoMethod();
	    break;
	case ITEM0 + 3:
	   if(!TextUtils.isEmpty(soundpath)){
	       f.delectFile(soundpath);
	   }
	    soundRecorderMethod();
	    break;

	default:
	    break;
	}
	return super.onOptionsItemSelected(item);
    }

    // 拍摄视频
    private void videoMethod() {
	Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
	FileNameUtil f = new FileNameUtil();
	videopath = f.SDCardPath("order/video");
	String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".avi";
	videopath=videopath+"/"+fileName;
	File out = new File(videopath);
	
	Uri uri = Uri.fromFile(out);
	intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
	intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
	startActivityForResult(intent, REQUEST_CODE_TAKE_VIDEO);
    }

    /**
     * 发送短息
     */
    public void sendMSM(String number, String name) {
	Uri smsToUri = Uri.parse("smsto:" + number);
	Intent sendIntent = new Intent(Intent.ACTION_VIEW, smsToUri);

	sendIntent.putExtra("sms_body", "尊敬的" + name + "用户:你的水表已绑定RFID卡");

	startActivity(sendIntent);
	System.out.println("发短息");
    }

    // 录音功能
    private void soundRecorderMethod() {
	Intent intent = new Intent(Media.RECORD_SOUND_ACTION);
	
	startActivityForResult(intent, REQUEST_CODE_TAKE_SOUND);
    }

    // 执行回调函数
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	if (requestCode == REQUEST_CODE_TAKE_VIDEO) {
	    System.out.println("返回视频");
	    if (resultCode == RESULT_OK) {
		   
	    }
	} else if (requestCode == REQUEST_CODE_TAKE_IMAGE) {
	    if (resultCode == RESULT_OK) {
		isImg=true;
	    }
	} else if (requestCode == REQUEST_CODE_TAKE_SOUND) {
	    if (resultCode == RESULT_OK) {
		Uri uriVideo = data.getData();
		Cursor cursor = this.getContentResolver().query(uriVideo, null, null, null, null);
		if (cursor.moveToNext()) {
		    String strVideoPath = cursor.getString(cursor.getColumnIndex("_data"));
		    FileInputStream fin = null;
		    FileOutputStream fout = null;
		    File file = new File(strVideoPath);
		    try {
			fin = new FileInputStream(file);

			FileNameUtil f = new FileNameUtil();
			soundpath = f.SDCardPath("order/sound");
			if (soundpath == null) {
			    Toast.makeText(OrderAddNoRfidActivity.this, "SD卡不可用", Toast.LENGTH_LONG).show();
			    return;
			}
			String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".amr";
			soundpath = soundpath + "/" + fileName;
			System.out.println(soundpath);
			fout = new FileOutputStream(soundpath);

			byte[] buffer = new byte[1024];
			int bytesRead;
			while ((bytesRead = fin.read(buffer)) > 0) {

			    fout.write(buffer, 0, bytesRead);
			}
			fin.close();
			fout.close();
		    } catch (FileNotFoundException e) {

			e.printStackTrace();
		    } catch (IOException e) {

			e.printStackTrace();
		    } finally {
			file.delete();
		    }

		}
	    }
	}
	super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
	Dialog dialog = null;
	switch (id) {

	case DIALOG + 1:
	    Builder builder1 = new android.app.AlertDialog.Builder(this);
	    // 设置对话框的图标
	    builder1.setIcon(R.drawable.buttondraw);
	    builder1.setTitle("确定添加新的工程单？");
	    builder1.setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
		    if (TextUtils.isEmpty(type)||type.equals("无")) {
			Toast.makeText(OrderAddNoRfidActivity.this, "你还没选择类型！", Toast.LENGTH_LONG).show();
			return;
		    }
		    boolean b = save();
		    if (b) {
			Toast.makeText(OrderAddNoRfidActivity.this, "添加数据成功", Toast.LENGTH_LONG).show();

		    }

		}
	    });
	    builder1.setNeutralButton("取消", new android.content.DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {

		}
	    });
	    // 创建一个单选按钮对话框
	    dialog = builder1.create();
	    break;
	}
	return dialog;
    }

    /**
     * 保存
     * 
     * @return
     */
    public boolean save() {
	boolean b = false;
	
	ContentValues values = new ContentValues();
	values.put("ordername", edit1.getEditableText().toString());
	values.put("desc", edit2.getEditableText().toString());
	values.put("soundpath", soundpath);
	values.put("videopath", videopath);
	values.put("status", "0");
	values.put("latitude", latitude);
	values.put("longitude", longitude);
       values.put("ordertype",type );
       values.put("deviceid", deviceid);
         if(isImg){
             values.put("isimg", "1");
         }else{
             values.put("isimg", "0");
         }
	b=dao.modifyOrder(values, OrderID+"");
	return b;

    }

    /**
     * 修改
     * 
     * @return
     */
    public boolean modify() {
	return false;
	
    }

    /**
     * 上传更新消息
     */
    Handler myHandler = new Handler() {

	@Override
	public void handleMessage(Message msg) {
	    pd.dismiss();

	    if (msg.what == 2) {
		
	    } else {
		Toast.makeText(OrderAddNoRfidActivity.this, "上传失败", Toast.LENGTH_LONG).show();
	    }
	}

    };

   
 

 
   
    @Override
    protected void onDestroy() {
	dao.delectOrderNoAdd(OrderID+"");
	dao.close();
	super.onDestroy();
    }
    
    
}
